package example;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

/**
 * Created by Administrator on 2016/9/21 0021.
 */
public class WholeFileRecordReader extends RecordReader<NullWritable, BytesWritable> {

    private boolean processed = false;
    private FileSplit fileSplit;
    private Configuration conf;
    private BytesWritable value = new BytesWritable();


    @Override
    public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
        fileSplit = (FileSplit) split;
        conf = context.getConfiguration();
    }

    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {
        if (!processed) {
            Path path = fileSplit.getPath();
            FileSystem fs = path.getFileSystem(conf);
            FSDataInputStream input = null;

            try {
                byte[] content = new byte[(int) fileSplit.getLength()];
                input = fs.open(path);
                IOUtils.readFully(input, content, 0, content.length);
                value.set(content, 0, content.length);
            } finally {
                IOUtils.closeStream(input);
            }

            processed = true;
            return true;
        } else {

            return false;
        }
    }

    @Override
    public NullWritable getCurrentKey() throws IOException, InterruptedException {
        return NullWritable.get();
    }

    @Override
    public BytesWritable getCurrentValue() throws IOException, InterruptedException {
        return value;
    }

    @Override
    public float getProgress() throws IOException, InterruptedException {
        return processed ? 1.0f : 0.0f;
    }

    @Override
    public void close() throws IOException {

    }
}
